/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package verification;

import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * This class makes sure that text entered into a JFormattedTextField is properly formatted as follows
 *  1. Not null (empty)
 *  2. Doesn't contain any illegal characters
 *  3. Is the proper length
 *  4. I'm sure there are more
 * 
 * @author NATHAN
 */
public class TextFieldVerifier extends AbstractValidator {

  private int minLength, maxLength;

  public TextFieldVerifier(JPanel parent, JComponent c, String message, int minLength, int maxLength) {
    super(parent, c, message);
    this.minLength = minLength;
    this.maxLength = maxLength;
  }

  @Override
  protected boolean validationCriteria(JComponent c) {
    String text = ((JTextField) c).getText();
    text = text.trim();

    // empty check
    if ("".equals(text)) {
    } else // length check
    if (!(text.length() <= maxLength && text.length() >= minLength)) {
      setMessage("Must be at least " + minLength + " and no more than " + maxLength + " characters long.");
      return false;
    } else { // illegal character check
      for (int i = 0; i < text.length(); i++) {
        if (!Character.isLetterOrDigit(text.charAt(i))) {
          setMessage("Only letters and numbers allowed.");
          return false;
        }
      }
    }
    return true;
  }
}
